// pages/airport/address.js
var util = require('../../network_util.js');
var config = require('../../config.js');
var commonjs = require('../../common.js');
var amapFile = require('../../libs/amap-wx.js');

var keywords = '';
var tips = {};
// var sltCity = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cityList: [],
    tips: {},
    destCityName: "",
    latestAddress: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var destCityName = wx.getStorageSync("destCityName");
    //先从缓存里取，如果没有的话取定位到的城市
    if (!commonjs.isEmpty(destCityName)) {
      console.log("address.onload.01");
      //从缓存获取到地点
      that.setData({ destCityName: destCityName });
      wx.setStorageSync("destCityName", that.data.destCityName);
      //从缓存获取之前搜索过的地名
      that.getLatestTips();
    } else {
      var fromCityName = wx.getStorageSync("fromCityName");
      if (!commonjs.isEmpty(fromCityName)) {
        console.log("address.onload.02");
        //从fromCityName获取到地点
        that.setData({ destCityName: fromCityName });
        wx.setStorageSync("destCityName", that.data.destCityName);
        //从缓存获取之前搜索过的地名
        that.getLatestTips();
      } else {
        var localCityName = wx.getStorageSync("localCityName");
        if (!commonjs.isEmpty(localCityName)) {
          console.log("address.onload.03");
          //从localCityName获取到地点
          that.setData({ destCityName: localCityName });
          wx.setStorageSync("destCityName", that.data.destCityName);
          //从缓存获取之前搜索过的地名
          that.getLatestTips();
        } else {
          console.log("address.onload.04");
          wx.showLoading({ title: "定位中...", mask: true });
          var key = config.aMapKey;
          var myAmapFun = new amapFile.AMapWX({ key: key });
          myAmapFun.getRegeo({
            iconPath: "../../images/marker.png",
            iconWidth: 22,
            iconHeight: 32,
            success: function (data) {
              wx.hideLoading();
              console.log("address.onload.04.1");
              console.log(data);
              var cityName = data[0].regeocodeData.addressComponent.city;
              that.setData({ localCityName: cityName });
              wx.setStorageSync("localCityName", cityName);
              //从定位获取到地点
              that.setData({ destCityName: cityName });
              wx.setStorageSync("destCityName", that.data.destCityName);
              //从缓存获取之前搜索过的地名
              that.getLatestTips();
            },
            fail: function (info) {
              console.log("address.onload.04.2");
              // wx.showModal({title:info.errMsg})
            },
            complete: function(res){
              console.log("address.onload.04.3");
            }
          })
        }
      }
    }
  },
  getLatestTips: function () {
    console.log("address.getLatestTips...");
    var latestTips = wx.getStorageSync(this.data.destCityName);
    if (latestTips != "") {
      this.setData({ tips: JSON.parse(latestTips) });
    } else {
      this.setData({ tips: {} });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("address.onReady...");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  changeCity: function () {
    wx.navigateTo({
      url: 'city',
    })
  },
  onAddressInput: function (e) {
    // console.log("sltCity=" + sltCity);
    var that = this;
    var myAmapFun = new amapFile.AMapWX({ key: config.aMapKey });
    myAmapFun.getInputtips({
      keywords: e.detail.value,
      location: '',
      city: that.data.destCityName,
      success: function (data) {
        console.log(data);
        if (data && data.tips) {
          var tmp = [];
          data.tips.forEach(function (itm, idx) {
            //过滤坐标为空的地址
            console.log(idx + ": " + itm.location.length);
            if (!commonjs.isEmpty(itm.location) && itm.location.length > 0)             {
              if (itm.address.length > 26) {
                itm.address = '';
              }
              tmp.push(itm);  
            }
          })
           console.log(tmp);
           that.setData({
            tips: tmp
          });
        }
        // console.log(tips);
      }
    });
  },
  onAddressItemTap: function (e) {
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页面 
    var prevPage = pages[pages.length - 2]; //上一个页面 
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去 
    // this.setData({ latestAddress: e.currentTarget.dataset.text});

    var latestTips = new Array();
    console.log("wx.getStorageSync . latestTips=");
    console.log(wx.getStorageSync(this.data.destCityName));
    if (wx.getStorageSync(this.data.destCityName) && wx.getStorageSync(this.data.destCityName) != "") {
      latestTips = JSON.parse(wx.getStorageSync(this.data.destCityName));
    }

    var newItem = {
      "name": e.currentTarget.dataset.text
      , "district": e.currentTarget.dataset.district
      , "address": e.currentTarget.dataset.address
      , "location": e.currentTarget.dataset.location
    };
    if (commonjs.arrContains(latestTips, newItem)) {
      //如果有了，就把这条删掉，在最后再插入这条

    } else {
      //如果没有，先判断是不是>5
      if (latestTips.length >= 5) { //大于的话，删掉最早那条，在最后再插入这条；
        latestTips.pop();
        latestTips.unshift(newItem);
      } else { //不大于的话，直接在最后插入这条
        latestTips.unshift(newItem);
      }
    }
    console.log("latestTips: " + JSON.stringify(latestTips));
    wx.setStorageSync(this.data.destCityName, JSON.stringify(latestTips));

    console.log("e.currentTarget=");
    console.log(e.currentTarget);
    prevPage.setData({ destination: e.currentTarget.dataset.text })
    prevPage.setData({ destinationLL: e.currentTarget.dataset.location })
    prevPage.setData({ destinationCityName: this.data.destCityName })
    wx.setStorageSync("destInfo", 
        {
          destination:e.currentTarget.dataset.text
          , destinationLL: e.currentTarget.dataset.location
          , destinationCityName: this.data.destCityName
          });
    
    // prevPage.getOriginLongNLang();
    prevPage.getDrivingRoute();
    wx.navigateBack({

    })
  },
  onCancle: function () {
    wx.navigateBack({

    })
  }
})
